//
//  ZallTextClickLabel.m
//  ZJS
//
//  Created by qingqiu.yuan on 16/9/18.
//  Copyright © 2016年 zall. All rights reserved.
//

#import "ZallTextClickLabel.h"

@interface ZallTextClickLabel()

@property (nonatomic, strong) NSString *stringText; //全部文本
@property (nonatomic, assign) CGFloat fontSize; //文字字号
@property (nonatomic, assign) CGFloat maxWidth; //文字限制宽度
@property (nonatomic, weak) id<ZallTextClickLabelDelegate>labelDelegate;
@property (nonatomic, assign) NSRange linkRange;


@end

@implementation ZallTextClickLabel

- (instancetype)initWithDelegate:(id)delegate {
    self = [super init];
    if (self) {
        self.labelDelegate = delegate;
        [self setUserInteractionEnabled:YES];
        [self setNumberOfLines:0];
    }
    return self;
}

- (void)setFontSize:(CGFloat)fontSize maxWidth:(CGFloat)width allText:(NSString *)allText linkRange:(NSRange)linkRange {
    self.stringText = allText;
    self.font = [UIFont systemFontOfSize:fontSize];
    self.fontSize = fontSize;
    self.maxWidth = width;
    self.linkRange = linkRange;
}

- (instancetype)initWithFontSize:(CGFloat)fontSize maxWidth:(CGFloat)width allText:(NSString *)allText linkRange:(NSRange)linkRange delegate:(id)delegate {
    self = [super init];
    if (self) {
        self.stringText = allText;
        self.font = [UIFont systemFontOfSize:fontSize];
        self.fontSize = fontSize;
        self.maxWidth = width;
        self.labelDelegate = delegate;
        self.linkRange = linkRange;
        [self setUserInteractionEnabled:YES];
        [self setNumberOfLines:0];
    }
    return self;
}

- (void)labelBlockWithLeftGap:(CGFloat)leftGap topGap:(CGFloat)topGap linkTextColor:(UIColor *)linkColor otherTextColor:(UIColor *)otherColor labelBlock:(LabelBlock)labelBlock {
    if ((NSInteger)self.stringText.length < 0 || (NSInteger)self.linkRange.length < 0 || (NSInteger)self.linkRange.location < 0) {
        return;
    }
    NSInteger temp = (NSInteger)self.stringText.length - (NSInteger)self.linkRange.location;
    if ( temp < 0 || temp - (NSInteger)self.linkRange.length < 0) {
        return;
    }
    
    CGSize size = [self boundingRectWithSize:CGSizeMake(self.maxWidth, CGFLOAT_MAX) stringStr:self.stringText fondSize:self.fontSize];
    //设置label位置
    [self setFrame:CGRectMake(leftGap, topGap, size.width, size.height)];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.stringText];//根据整个字符串转成的富文本
    NSInteger beforeLinkTextLong =  self.stringText.length - self.linkRange.location;
    //如果可点击区域在这个文本的中间，设置可点击区域左边的文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:otherColor range:NSMakeRange(0,[str length] - beforeLinkTextLong)];
    //如果可点击区域在这个文本的中间，设置可点击区域右边边的文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:otherColor range:NSMakeRange(self.linkRange.location + self.linkRange.length,self.stringText.length - (self.linkRange.location + self.linkRange.length))];
    //设置可点击区域文本的文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:linkColor range:NSMakeRange(self.linkRange.location,self.linkRange.length)];
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineSpacing = 5.0f;
    paragraph.headIndent = self.headIndent;
    [str addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, self.stringText.length)];
    self.attributedText = str;
    
    labelBlock(self);
}

- (BOOL)isClickLink:(CGPoint)point {
    NSString *beForeText = [self.stringText substringToIndex:self.linkRange.location];
    //self.range.location 之前的文字size
    CGSize beforSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) stringStr:beForeText fondSize:self.fontSize];
    
    //获取self.range.location 之前的信息
    NSInteger beForA = beforSize.width / self.maxWidth;//选中文字之前的文字宽度，是否到了最大宽度
    NSInteger beForW = beforSize.width;
    NSInteger beForB = (NSInteger)beForW % (NSInteger)self.maxWidth;
    
    //从第0位开始包含选中文字的字符串
    NSString *beForEndText = [self.stringText substringToIndex:self.linkRange.location+self.linkRange.length];
    //从第0位开始包含选中文字的字符串大小
    CGSize beforEndSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) stringStr:beForEndText fondSize:self.fontSize];
    //获取self.range.location 之前的信息
    NSInteger beForEndA = beforEndSize.width / self.maxWidth; //从第0位开始包含选中文字的字符串宽度，是否到了最大宽度
    NSInteger beForEndW = beforEndSize.width;
    NSInteger beForEndB = (NSInteger)beForEndW % (NSInteger)self.maxWidth;
    
    //self.range范围的文字没有折行情况(在同一行) 则不需要考虑下一行的点击
    if (beForEndA == beForA) {
        if (beForA == 0 && point.x > beForB && point.x < beForEndB && point.y < beforSize.height) {
            //可点击区域没有折行
            return YES;
            //beForA > 0 b 并且被点击的文字在同一行
        }else {
            if (point.y > beForA * beforSize.height && point.x > beForB && point.y < beForA * beforSize.height + beforSize.height && point.x < beForEndB) {
                //ZallLog(@"没有折行 >0行 点击了");
                return YES;
            }
        }
    }else {
        //self.range范围的文字不再同一行 则需要考虑下一行的点击 因为部分文在在下一行
        if ((beForA == 0 && point.x > beForB && point.y < beforSize.height) || (beForA == 0 && point.x < beForEndB && point.y>beforSize.height && point.y < beForEndA*beforEndSize.height + beforEndSize.height)) {
            //ZallLog(@"不再同一行 且为beForA = 0行 点击了");
            return YES;
        }else {
            if ((beForA > 0 && point.x>beForB && point.y > beForA*beforEndSize.height
                 && point.y<beForEndA*beforEndSize.height) ||
                (beForA > 0 && point.x<beForEndB && point.y > beForEndA*beforEndSize.height && point.y < (beForEndA+1)*beforEndSize.height)) {
                //ZallLog(@"不再同一行 且beForA > 0行 点击了");
                return YES;
            }
        }
    }
    return NO;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    
    //当前点击的位置
    CGPoint point = [touch locationInView:self];
    if ([self isClickLink:point] && self.labelDelegate && [self.labelDelegate respondsToSelector:@selector(clickLabel:didClickText:)]) {
        [self.labelDelegate clickLabel:self didClickText:[self.stringText substringWithRange:self.linkRange]];
    }
}

- (CGSize)boundingRectWithSize:(CGSize)size stringStr:(NSString *)stringStr fondSize:(CGFloat)fontOfSize {
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = 5.0; //设置行间距
    
    NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:fontOfSize], NSParagraphStyleAttributeName:paraStyle};
    
    CGSize retSize = [stringStr boundingRectWithSize:size
                                             options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                          attributes:attribute
                                             context:nil].size;
    
    return retSize;
}

- (void)setLabelTag:(NSUInteger)labelTag {
    [self willChangeValueForKey:@"labelTag"];
    _labelTag = labelTag;
    [self didChangeValueForKey:@"labelTag"];
}

- (void)setHeadIndent:(CGFloat)headIndent {
    [self willChangeValueForKey:@"headIndent"];
    _headIndent = headIndent;
    [self didChangeValueForKey:@"headIndent"];
}
@end
